const Discuss_Model = require('../models/DiscussModel')




const DiscussService = {
    add_discuss: async (data) => {

        return Discuss_Model.create({
            ...data
        })
    },
    find_discuss: async (id) => {
        //id:'文章'分类的id
        //temp用于存储顶级评论
        let temp = []
        //deeplist:递归函数，parent_comment_id：传入上一级评论id,idx顶级评论当前索引值
        async function deeplist(parent_comment_id, idx = 0) {
            //aggregate集合管道,
            const comments = await Discuss_Model.aggregate([
                {
                    // 匹配顶级评论，
                    $match: { parent_comment_id: parent_comment_id, article_id: id, isDelete: false }
                },

                {
                    /**
                     * 将$user_id转化为ObjectId对象作为新字段：userIdObject，
                     * 此文档字段user_id为字符串类型与_id(ObjectId)类型进行匹配时需要转化，否则没有结果
                     */
                    $addFields: {
                        // parent_id: { $toObjectId: "$parent_comment_id" },
                        // 将 userId 转换为 ObjectId 类型
                        userIdObject: { $toObjectId: "$user_id" },

                        publish_date: {
                            $dateToString: {
                                format: "%Y-%m-%d %H:%M", // 转换为年月日格式
                                date: { $toDate: "$comment_date" },
                                timezone: "Asia/Shanghai"// 将时间戳转换为日期
                            }
                        }
                    }
                },
                //联表查询，评论表和用户表
                {
                    $lookup: {
                        //联表查询的目标
                        from: "commonusers",
                        //当前表中需要进行关联的字段，
                        localField: "userIdObject",
                        //要被关联的目标表中的字段
                        foreignField: '_id',
                        //给结果数组中字段取个名称
                        as: "user"
                    }
                },
                {// 展开数组，获取第一个匹配的用户信息
                    $unwind: '$user'
                },
                {
                    //最后返回前需要保留的字段，1保存，
                    $project: {
                        _id: 1,
                        article_id: 1,
                        user_id: 1,
                        comment_text: 1,
                        comment_date: 1,
                        parent_comment_id: 1,
                        publish_date: 1,
                        'user.username': 1,
                        'user.avatar': 1,
                        'user.role': 1
                    }
                }

            ])
            if (parent_comment_id === '') {
                //拿到所有一楼的评论
                temp = comments
                for (let i = 0; i < temp.length; i++) {
                    temp[i].childs = []
                }
                return
            }
            if (comments.length === 0) {
                return []
            }
            temp[idx].childs = temp[idx].childs.concat(comments)
            for (let i = 0; i < comments.length; i++) {
                await deeplist(comments[i]._id.toString(), idx)
            }
            return comments
        }
        async function deeplist2(parent_comment_id, idx = 0) {
            //aggregate集合管道,
            const comments = await Discuss_Model.aggregate([
                {
                    // 匹配顶级评论，
                    $match: { parent_comment_id: parent_comment_id, article_id: id, isDelete: false }
                },

                {
                    /**
                     * 将$user_id转化为ObjectId对象作为新字段：userIdObject，
                     * 此文档字段user_id为字符串类型与_id(ObjectId)类型进行匹配时需要转化，否则没有结果
                     */
                    $addFields: {
                        parent_id: { $toObjectId: "$parent_comment_id" },
                        // 将 userId 转换为 ObjectId 类型
                        userIdObject: { $toObjectId: "$user_id" },

                        publish_date: {
                            $dateToString: {
                                format: "%Y-%m-%d %H:%M", // 转换为年月日格式
                                date: { $toDate: "$comment_date" },// 将时间戳转换为日期

                                timezone: "Asia/Shanghai"
                            }
                        }
                    }
                },
                //联表查询，评论表和用户表
                {
                    $lookup: {
                        //联表查询的目标
                        from: "commonusers",
                        //当前表中需要进行关联的字段，
                        localField: "userIdObject",
                        //要被关联的目标表中的字段
                        foreignField: '_id',
                        //给结果数组中字段取个名称
                        as: "user"
                    }
                },
                {// 展开数组，获取第一个匹配的用户信息
                    $unwind: '$user'
                },
                {
                    $lookup: {
                        from: "discusses",
                        localField: "parent_id",
                        //要被关联的目标表中的字段
                        foreignField: '_id',
                        as: "parent"
                    }
                },
                {
                    $unwind: {
                        path: '$parent',
                        preserveNullAndEmptyArrays: true
                    }
                },
                {
                    $addFields: {
                        'parent.user_id': { $toObjectId: "$parent.user_id" },
                    }
                },
                {
                    $lookup: {
                        from: 'commonusers',
                        localField: 'parent.user_id',
                        foreignField: '_id',
                        as: 'parent.user'
                    }
                },
                {
                    $unwind: {
                        path: '$parent.user',
                        preserveNullAndEmptyArrays: true
                    }
                },
                {
                    //最后返回前需要保留的字段，1保存，
                    $project: {
                        _id: 1,
                        article_id: 1,
                        user_id: 1,
                        comment_text: 1,
                        comment_date: 1,
                        parent_comment_id: 1,
                        publish_date: 1,
                        'parent.user.username': 1,
                        'user.username': 1,
                        'user.avatar': 1,
                        'user.role': 1
                    }
                }

            ])
            if (parent_comment_id === '') {
                //拿到所有一楼的评论
                temp = comments
                for (let i = 0; i < temp.length; i++) {
                    temp[i].childs = []
                }
                return
            }
            if (comments.length === 0) {
                return []
            }
            temp[idx].childs = temp[idx].childs.concat(comments)
            for (let i = 0; i < comments.length; i++) {
                await deeplist2(comments[i]._id.toString(), idx)
            }
            return comments
        }
        await deeplist('')
        for (let i = 0; i < temp.length; i++) {
            await deeplist2(temp[i]._id.toString(), i)
        }
        return temp

    },
    //后台
    find_discuss_back: async (skp = 0, artice_type = 'essay') => {
        if (artice_type == 'essay') {
            const data = await Discuss_Model.aggregate([
                {

                    $facet: {
                        totalCount: [
                            { $match: { dis_type: "essay", isDelete: false } },
                            { $count: 'count' },
                            {
                                $addFields: {
                                    totalCount: { $arrayElemAt: ['$totalCount.count', 0] }
                                }
                            },
                        ],
                        dislist: [
                            { $match: { isDelete: false } },
                            {
                                $addFields: {
                                    user_obj_id: { $toObjectId: "$user_id" },
                                    article_id_obj: { $toObjectId: "$article_id" },
                                    format_time: {
                                        $dateToString: {
                                            format: "%Y-%m-%d %H:%M",
                                            date: {
                                                $toDate: "$comment_date"
                                            },
                                            timezone: "Asia/Shanghai"
                                        }
                                    },

                                }
                            }
                            ,
                            {
                                $lookup: {
                                    from: "commonusers",
                                    localField: "user_obj_id",
                                    foreignField: "_id",
                                    as: "user"
                                }
                            },
                            {
                                $unwind: "$user"
                            },
                            {
                                $lookup: {
                                    from: "essays",
                                    localField: "article_id_obj",
                                    foreignField: "_id",
                                    as: "article"
                                }
                            },
                            {
                                $unwind: "$article"
                            },
                            {
                                $project: {
                                    comment_text: 1,
                                    format_time: 1,
                                    "user.username": 1,
                                    "article.title": 1
                                }
                            },
                            {
                                $sort: { 'format_time': -1 }
                            },
                            {
                                $skip: skp

                            },
                            {
                                $limit: 10,
                            },

                        ]
                    }
                },
                {
                    $project: {
                        totalCount: { $arrayElemAt: ['$totalCount.count', 0] },
                        dislist: 1
                    }
                }

            ])

            return data
        } else {
            const data = await Discuss_Model.aggregate([
                {
                    $facet: {
                        totalCount: [
                            { $match: { dis_type: "video", isDelete: false } },
                            { $count: 'count' },
                            {
                                $addFields: {
                                    totalCount: { $arrayElemAt: ['$totalCount.count', 0] }
                                }
                            },
                        ],
                        dislist: [
                            { $match: { isDelete: false } },
                            {
                                $addFields: {
                                    user_obj_id: { $toObjectId: "$user_id" },
                                    article_id_obj: { $toObjectId: "$article_id" },
                                    format_time: {
                                        $dateToString: {
                                            format: "%Y-%m-%d %H:%M",
                                            date: {
                                                $toDate: "$comment_date"
                                            },
                                            timezone: "Asia/Shanghai"
                                        }
                                    },

                                }
                            }
                            ,
                            {
                                $lookup: {
                                    from: "commonusers",
                                    localField: "user_obj_id",
                                    foreignField: "_id",
                                    as: "user"
                                }
                            },
                            {
                                $unwind: "$user"
                            },
                            {
                                $lookup: {
                                    from: "videos",
                                    localField: "article_id_obj",
                                    foreignField: "_id",
                                    as: "article"
                                }
                            },
                            {
                                $unwind: "$article"
                            },
                            {
                                $project: {
                                    comment_text: 1,
                                    format_time: 1,
                                    "user.username": 1,
                                    "article.title": 1
                                }
                            },
                            {
                                $sort: { 'format_time': -1 }
                            },
                            {
                                $skip: skp

                            },
                            {
                                $limit: 10,
                            },
                        ]
                    }
                },
                {
                    $project: {
                        totalCount: { $arrayElemAt: ['$totalCount.count', 0] },
                        dislist: 1
                    }
                }
            ])
            return data
        }

    },
    deleteone: async (id) => {
        return Discuss_Model.updateOne({
            _id: id
        }, {
            isDelete: true
        })
    }
}


module.exports = DiscussService

